/*
 * Canvas Game Engine - Text Handler
 *
 * version: 0.1
 * 
 * author: Fabio Rotondo <fabio@rotondo.it>
 */

function CGEText ( th, name, text, size, font_name, mode )
{
	this.th = th;

	this.text = text;
	this.size = size ? size : 30;

	this.fill = "#ff0000";
	this.stroke = "#000000";

	this.weight = "normal";
	this.style = "normal";

	this.set_mode ( mode );
	this.set_font ( font_name );

	this.x = 0;
	this.y = 0;
}

CGEText.prototype.set_mode = function ( mode )
{
	switch ( mode )
	{
		case "stroke":
			this.mode = "strokeText";
			break;
		default:
			this.mode = "fillText";
	}
};

CGEText.prototype.set_font = function ( mode )
{
	switch ( mode )
	{
		case "serif":
		case "cursive":
		case "fantasy":
		case "monospace":
			this.font_name = mode;

		default:
			this.font_name = "sans-serif";
	}
};

CGEText.prototype.set_weight = function ( mode )
{
	switch ( mode )
	{
		case "bold":
		case "bolder":
		case "lighter":
			this.weight = mode;

		default:
			this.weight = "normal";
	}
};

CGEText.prototype.set_style = function ( mode )
{
	switch ( mode )
	{
		case "italic":
		case "oblique":
			this.style = mode;

		default:
			this.style = "normal";
	}
};

CGEText.prototype.draw = function ( x, y, alpha )
{
	var ctxt = CGE.canvas.ctxt;

	if ( x === undefined ) x = this.x;
	if ( y === undefined ) y = this.y;

	this.x = x; this.y = y;

	ctxt.save ();

	this._prepare_style ( ctxt );

	if ( alpha !== undefined ) ctxt.globalAlpha = alpha / 100;
	ctxt.fillStyle = this.fill;
	ctxt.strokeColor = this.stroke;
	ctxt [ this.mode ] ( this.text, this.x, this.y );

	ctxt.restore ();
};

CGEText.prototype.get_width = function ( txt )
{
	var ctxt = CGE.canvas.ctxt;
	var width;

	txt = txt ? txt : this.text;

	ctxt.save ();
	this._prepare_style ( ctxt );
	width = ctxt.measureText ( this.text );
	ctxt.restore ();

	return width;
};

CGEText.prototype._prepare_style = function ( ctxt )
{
	ctxt.font = this.style + " " + this.weight + " " + this.size + "px " + this.font_name;
};



function CGETextHandler ()
{
	this.texts = {};
}

CGETextHandler.prototype.add = function ( name, text, size, font_name, mode )
{
	var i;

	// You cannot have two texts with the same ID
	if ( this.texts [ name ] ) return this.texts [ name ];

	i = new CGEText ( this, name, text, size, font_name, mode );
	this.texts [ name ] = i;

	return i;
};

CGETextHandler.prototype.get = function ( name )
{
	return this.texts [ name ];
};

CGETextHandler.prototype.ready = function () { return true; };

// Register the TextHandler to the system
CGE.register ( "text_handler", new CGETextHandler () );
